package com.wanban.downloader.db.room

import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.wanban.downloader.db.DownloadEntity

@Dao
interface DownloadDao {

    @get:Query("SELECT * FROM downloadentity")
    val allTasks: List<DownloadEntity>?

    @Query("SELECT * FROM downloadentity WHERE state!=:successStatus AND state!=:deleteStatus")
    fun getRunningTasks(successStatus: Int, deleteStatus: Int): List<DownloadEntity>?

    @Query("SELECT * FROM downloadentity WHERE videoId=:videoId AND state=:status")
    fun getTasksByVideoIdAndStatus(videoId: Long, status: Int): List<DownloadEntity>?

    @Query("SELECT * FROM downloadentity WHERE videoId=:videoId AND sourceId=:sourceId")
    fun getTasksByVideoIdAndSourceId(videoId: Long, sourceId: Int): List<DownloadEntity>?

    @Query("SELECT * FROM downloadentity WHERE videoId=:videoId AND sourceId=:sourceId AND episode=:episode")
    fun getTasksByVideoAndSourceIdAndEpisode(videoId: Long, sourceId: Int, episode: Int): DownloadEntity?

    @Query("SELECT * FROM downloadentity WHERE videoId=:videoId AND state=:status AND episode=:episode")
    fun getTaskByVideoIdAndEpisodeAndStatus(videoId: Long, episode: Int, status: Int): List<DownloadEntity>?

    @Query("SELECT * FROM downloadentity WHERE videoId=:videoId AND episode=:episode")
    fun getTasksByVideoIdAndEpisode(videoId: Long, episode: Int): List<DownloadEntity>?

    @Query("SELECT * FROM downloadentity WHERE url=:url")
    fun getTaskByUrl(url: String?): DownloadEntity?

    @Query("SELECT * FROM downloadentity WHERE state=:targetStatus")
    fun getTasksByStatus(targetStatus: Int): List<DownloadEntity>?

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(entity: DownloadEntity)

    @Query("DELETE FROM downloadentity WHERE url=:url")
    fun delete(url: String)

    @Query("DELETE FROM downloadentity")
    fun deleteAll()

    @Query("SELECT * FROM downloadentity WHERE videoName=:videoName AND sourceId=:sourceId AND episode=:episode")
    fun getTasks(videoName: String?, episode: Int, sourceId: Int): List<DownloadEntity>?

    companion object {
        const val column =
            "url, videoName, coverUrl, videoId, state, episode, percent, sourceId, category, watchTime, retryTime, contentLength, filePath, fromUrl, " +
                    "episodeName, coverFilePath, header, errorMsg, fileDirPath"
    }
}